<?php

namespace app\user\controller\questionnaire\result;

use app\admin\service\UserService;
use app\BaseController;
use app\model\questionnaire\QuestionnaireTaskModel;
use app\model\questionnaire\QuestionnaireTaskUserModel;
use app\model\questionnaire\QuestionnaireTaskUserResultModel;
use think\App;

class Index extends BaseController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * 问卷测评记录-手机
     * @return bool|string
     */
    public function mobileLog(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            $ResultWhere = [];
            $QuestionnaireTaskModel = new QuestionnaireTaskModel();
            $QuestionnaireTaskUserModel = new QuestionnaireTaskUserModel();
            $QuestionnaireTaskUserResultModel = new QuestionnaireTaskUserResultModel();
            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $ResultWhere[] = ['time', 'between', [$param['start_time'], $param['end_time']]];
            } else {
                if (!empty($param['start_time'])) {
                    $ResultWhere[] = ['time', '>=', $param['start_time']];
                }
                if (!empty($param['end_time'])) {
                    $ResultWhere[] = ['time', '<=', $param['end_time']];
                }
            }
            $ResultWhere[] = ['user_del', '=', 0];
            $ResultWhere[] = ['uid', '=', $this->userData['id']];
            $taskList = $QuestionnaireTaskUserResultModel->where($ResultWhere)->field('task_id,time')->select()->toArray();
            $taskData = [];
            $completeData = [];
            foreach ($taskList as $v) {
                $taskData[$v['task_id']] = $v['time'];
                $completeData[$v['task_id']][] = 1;
            }
            $task_ids = array_column($taskList, 'task_id');
            $finishIds = $QuestionnaireTaskUserModel->where([
                ['task_id', 'in', $task_ids],
                ['uid', '=', $this->userData['id']],
                ['is_finish', '=', 0]
            ])->distinct(true)->column('task_id');
            if (isset($param['is_finish']) && strlen($param['is_finish']) > 0) {
                if ($param['is_finish'] == 1) {
                    $task_ids = array_diff($task_ids, $finishIds);
                    if (!empty($task_ids)) {
                        $where[] = ['id', 'in', $task_ids];
                    } else {
                        $where[] = ['id', '=', -1];
                    }
                } else {
                    if (!empty($finishIds)) {
                        $where[] = ['id', 'in', $finishIds];
                    } else {
                        $where[] = ['id', '=', -1];
                    }
                }
            } else {
                $where[] = ['id', 'in', $task_ids];
            }

            if (!empty($param['name'])){
                $where[] = ['name','like','%'.$param['name'].'%'];
            }
            if (!empty($param['uid'])){
                $where[] = ['uid','=',$param['uid']];
            }
            $query = $QuestionnaireTaskModel->where($where);
            $data = $query->with([
                'user'
            ])->order('id desc')->select()->toArray();
            $data2 = [];
            foreach ($data as &$item) {
                $item['user_complete_paper_num'] = count($completeData[$item['id']]??[]);
                $item['time'] = $taskData[$item['id']]??0;
                if (in_array($item['id'], $finishIds)) {
                    $item['is_finish'] = 0;
                } else {
                    $item['is_finish'] = 1;
                }
                $date = date('Y年m月份',$item['time']);
                $data2[$date][] = $item;
            }
            return success($data2);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 答卷结果列表
     * @return bool|string
     */
    public function index(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'pageSize|每页显示数量' => 'require',
            ]);
            $where = [];
            $ResultWhere = [];
            $QuestionnaireTaskModel = new QuestionnaireTaskModel();
            $QuestionnaireTaskUserModel = new QuestionnaireTaskUserModel();
            $QuestionnaireTaskUserResultModel = new QuestionnaireTaskUserResultModel();
            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $ResultWhere[] = ['time', 'between', [$param['start_time'], $param['end_time']]];
            } else {
                if (!empty($param['start_time'])) {
                    $ResultWhere[] = ['time', '>=', $param['start_time']];
                }
                if (!empty($param['end_time'])) {
                    $ResultWhere[] = ['time', '<=', $param['end_time']];
                }
            }
            $ResultWhere[] = ['uid', '=', $this->userData['id']];
            $taskList = $QuestionnaireTaskUserResultModel->where($ResultWhere)->field('task_id,time')->select()->toArray();
            $taskData = [];
            foreach ($taskList as $v) {
                $taskData[$v['task_id']] = $v['time'];
            }
            $task_ids = array_column($taskList, 'task_id');
            $finishIds = $QuestionnaireTaskUserModel->where([
                ['task_id', 'in', $task_ids],
                ['uid', '=', $this->userData['id']],
                ['is_finish', '=', 0]
            ])->column('task_id');
            $finishIds = array_unique($finishIds);
            if (!empty($param['is_finish']) || strlen($param['is_finish']) > 0) {
                if ($param['is_finish'] == 1) {
                    $task_ids = array_diff($task_ids, $finishIds);
                    if (!empty($task_ids)) {
                        $where[] = ['id', 'in', $task_ids];
                    } else {
                        $where[] = ['id', '=', -1];
                    }
                } else {
                    if (!empty($finishIds)) {
                        $where[] = ['id', 'in', $finishIds];
                    } else {
                        $where[] = ['id', '=', -1];
                    }
                }
            } else {
                $where[] = ['id', 'in', $task_ids];
            }

            if (!empty($param['name'])){
                $where[] = ['name','like','%'.$param['name'].'%'];
            }
            if (!empty($param['uid'])){
                $where[] = ['uid','=',$param['uid']];
            }
            $query = $QuestionnaireTaskModel->where($where);
            $data = $query->with([
                'user'
            ])->order('id desc')->paginate($param['pageSize'])->toArray();
            foreach ($data['data'] as &$item) {
                $item['time'] = $taskData[$item['id']]??0;
                if (in_array($item['id'], $finishIds)) {
                    $item['is_finish'] = 0;
                } else {
                    $item['is_finish'] = 1;
                }
            }
            $data['ids'] = $query->column('id');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 答卷结果详情（左、中）
     * @return bool|string
     */
    public function info(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require'
            ]);
            $QuestionnaireTaskModel = new QuestionnaireTaskModel();
            $QuestionnaireTaskUserModel = new QuestionnaireTaskUserModel();
            $taskInfo = $QuestionnaireTaskModel->with(['user'])->find($param['id']);
            $result = $QuestionnaireTaskUserModel->where([
                ['task_id', '=', $param['id']],
                ['uid', '=', $this->userData['id']],
                ['is_finish', '=', 1]
            ])->with([
                'user',
                'TaskUserResult',
                'paper'
            ])->select()->toArray();
            $taskInfo['finish_num'] = count($result);
            $taskInfo['result_total_score'] = array_sum(array_column($result,'result_total_score'));
            $taskInfo['result_time'] = 0;
            foreach ($result as $v) {
                if($v['result_time'] > $taskInfo['result_time']){
                    $taskInfo['result_time'] = $v['result_time'];
                }
            }
            return success([
                'taskInfo' => $taskInfo,
                'result' => $result
            ]);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 答卷结果详情（右）
     * @return bool|string
     */
    public function resultInfo(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require'
            ]);
            $QuestionnaireTaskUserResultModel = new QuestionnaireTaskUserResultModel();
            $info = $QuestionnaireTaskUserResultModel->with([
                'user' => function($query){
                    $query->with(['role_name']);
                },
                'paper' => function($query){
                    $query->with([
                        'typeName',
                        'paperTopic' => function ($query) {
                            $query->with([
                                'topic' => function ($query) {
                                    $query->with(['answer','img']);
                                }
                            ]);
                        }
                    ]);
                }
            ])->find($param['id']);
            if (!$info) throw new \Exception('未找到结果！');
            $info = $info->toArray();
            if ($info['user_del'] == 1) throw new \Exception('已被删除！');
            $question_answer = json_decode($info['question_answer'], true);
            $answerData = [];
            foreach ($question_answer as $v) {
                $answerData[$v['topic_id']] = $v;
            }
            foreach ($info['paperTopic'] as &$item){
                $item['topic']['question_answer'] = $answerData[$item['topic']['id']]??[];
            }
            $UserService = new UserService($this->app);
            $info['department_name'] = $UserService->getNotDelDepartmentName($this->userData['unit_id'],$info['department_id']);
            return success($info);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 删除整个任务的报告
     * @return bool|string
     */
    public function taskResultDel(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require'
            ]);
            $QuestionnaireTaskUserResultModel = new QuestionnaireTaskUserResultModel();
            $QuestionnaireTaskUserResultModel->where([
                ['task_id', 'in', $param['id']],
                ['uid', '=', $this->userData['id']],
            ])->update([
                'user_del' => 1
            ]);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 删除任务单个问卷的全部报告
     * @return bool|string
     */
    public function taskPaperResultDel(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
                'paper_id|问卷ID' => 'require'
            ]);
            $QuestionnaireTaskUserResultModel = new QuestionnaireTaskUserResultModel();
            $QuestionnaireTaskUserResultModel->where([
                ['task_id', '=', $param['id']],
                ['paper_id', '=', $param['paper_id']],
                ['uid','=',$this->userData['id']],
            ])->update([
                'user_del' => 1
            ]);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 删除单份报告
     * @return bool|string
     */
    public function del(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require'
            ]);
            $QuestionnaireTaskUserResultModel = new QuestionnaireTaskUserResultModel();
            $info = $QuestionnaireTaskUserResultModel->find($param['id']);
            if (!$info || $info['uid'] != $this->userData['id']) throw new \Exception('参数错误！');
            $info->save([
                'user_del' => 1
            ]);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }
}